function permuteUnique(nums: number[]): number[][] {
  const n = nums.length;
  const ans: number[][] = [];
  const used: boolean[] = new Array(n).fill(false);
  nums.sort((x, y) => x - y);
  recur(0, []);
  return ans;
  function recur(pos: number, arr: number[]) {
    if (pos === n) {
      ans.push([...arr]);
      return;
    }
    for (let i = 0; i < n; i++) {
      if (used[i] || (i > 0 && nums[i] === nums[i - 1] && !used[i - 1])) {
        continue;
      }
      arr.push(nums[i]);
      used[i] = true;
      recur(pos + 1, arr);
      used[i] = false;
      arr.pop();
    }
  }
};